package foodmaterial.action;

import com.github.pagehelper.PageInfo;
import foodmaterial.config.ChoiceDataSource;
import foodmaterial.dto.*;
import foodmaterial.entity.*;
import foodmaterial.excel.Excel;
import foodmaterial.service.InitService;
import foodmaterial.service.PurchaseService;
import foodmaterial.utils.Constants;
import foodmaterial.utils.FileTools;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/purchase")
@CrossOrigin(allowCredentials = "true")
public class PurchaseAction extends BaseAction{

    @Autowired
    private PurchaseService service ;

    @Autowired
    private InitService initService ;

    @Autowired
    private Excel excel;

    @PostMapping("/addSupplier")
    @ChoiceDataSource
    public JsonResult<String> addSupplier(@RequestBody @Valid Supplier supplier, BindingResult bindingResult) {
        JsonResult jsonResult = BindingResultUtil.error(bindingResult) ;
        if (jsonResult.getSuccess() == false) return jsonResult ;
        int result = service.addSupplier(supplier) ;
        return result > 0 ? JsonResultTool.get(jsonResult,true, "新增供应商成功") :
                JsonResultTool.get(jsonResult,false,"新增供应商失败") ;
    }

    @PostMapping("/modifySupplier")
    @ChoiceDataSource
    public JsonResult<String> modifySupplier(@RequestBody @Valid Supplier supplier, BindingResult bindingResult) {
        JsonResult jsonResult = BindingResultUtil.error(bindingResult) ;
        if (jsonResult.getSuccess() == false) return jsonResult ;
        int result = service.modifySupplier(supplier) ;
        return result > 0 ? JsonResultTool.get(jsonResult,true, "修改供应商成功") :
                JsonResultTool.get(jsonResult,false,"修改供应商失败") ;
    }

    @PostMapping("/querySupplierById")
    @ChoiceDataSource
    public JsonResult<Supplier> querySupplierById(@RequestBody SupplierDto dto) {
        Supplier result = service.querySupplierById(dto) ;
        return new JsonResult(true, ResultCode.SUCCESS,result) ;
    }

    @PostMapping("/querySuppliers")
    @ChoiceDataSource
    public JsonResult<PageInfo<Supplier>> querySuppliers(@RequestBody @Valid SupplierDto dto, BindingResult bindingResult) {
        JsonResult jsonResult = BindingResultUtil.error(bindingResult) ;
        if (jsonResult.getSuccess() == false) return jsonResult ;
        this.setPageHelper(dto.getPageNo(),dto.getPageSize()); ;
        List<Supplier> result = service.querySuppliers(dto) ;
        PageInfo<Supplier> pageInfo = new PageInfo<>(result) ;
        jsonResult.setData(pageInfo);
        jsonResult.setErrorMsg(ResultCode.SUCCESS.getMessage());
        return jsonResult ;
        //return new JsonResult(true, ResultCode.SUCCESS,pageInfo) ;
    }

    @PostMapping("/addPurchaseBill")
    @ChoiceDataSource
    public JsonResult<String> addPurchaseBill(@RequestBody @Valid PurchaseBill purchaseBill,
                                              BindingResult bindingResult) {
        JsonResult jsonResult = BindingResultUtil.error(bindingResult) ;
        if (jsonResult.getSuccess() == false) return jsonResult ;
        int result = service.addPurchaseBill(purchaseBill) ;
        return result > 0 ? JsonResultTool.get(jsonResult,true, "新增采购单成功") :
                JsonResultTool.get(jsonResult,false,"新增采购单失败") ;
    }

    @PostMapping("/modifyPurchaseBill")
    @ChoiceDataSource
    public JsonResult<String> modifyPurchaseBill(@RequestBody @Valid PurchaseBill purchaseBill,
                                                 BindingResult bindingResult) {
        JsonResult jsonResult = BindingResultUtil.error(bindingResult) ;
        if (jsonResult.getSuccess() == false) return jsonResult ;
        int result = service.modifyPurchaseBill(purchaseBill) ;
        return result > 0 ? JsonResultTool.get(jsonResult,true, "修改采购单成功") :
                JsonResultTool.get(jsonResult,false,"修改采购单失败") ;
    }

    @PostMapping("/queryPurchaseBill")
    @ChoiceDataSource
    public JsonResult<PageInfo<PurchaseBill>> queryPurchaseBill(@RequestBody @Valid PurchaseBillDto dto,BindingResult bindingResult) {
        JsonResult jsonResult = BindingResultUtil.error(bindingResult) ;
        if (jsonResult.getSuccess() == false) return jsonResult ;
        this.setPageHelper(dto.getPageNo(),dto.getPageSize()); ;
        List<PurchaseBill> result = service.queryPurchaseBill(dto) ;
        PageInfo<PurchaseBill> pageInfo = new PageInfo<>(result) ;
        jsonResult.setData(pageInfo);
        jsonResult.setErrorMsg(ResultCode.SUCCESS.getMessage());
        return jsonResult;
        //return new JsonResult(true, ResultCode.SUCCESS,pageInfo) ;
    }

    @GetMapping("/queryPurchaseBillDetails")
    @ChoiceDataSource
    public JsonResult<List<PurchaseBillDetails>> queryPurchaseBillDetails(Long purchaseBillId) {
        List<PurchaseBillDetails> result = service.queryPurchaseBillDetails(purchaseBillId) ;
        return new JsonResult(true, ResultCode.SUCCESS,result) ;
    }

    @GetMapping("/queryPurchaseBillById")
    @ChoiceDataSource
    public JsonResult<PurchaseBill> queryPurchaseBillById(Long id) {
        PurchaseBill pb = service.queryPurchaseBillById(id) ;
        return pb != null ? new JsonResult(true, ResultCode.SUCCESS,pb) :
                new JsonResult(false, "没有此订单") ;
    }

    @GetMapping("/printPurchaseBill")
    public ModelAndView print(@RequestParam("billIds") List<Long> ids) {
        Map<String,Object> map = new HashMap<>() ;
        String foodSupplyType = this.getSysUser().getFoodSupplyType() ;
        if (Constants.ORIGINAL_FOOD.equals(foodSupplyType)) map.put("originalProcess",false) ;
        else map.put("originalProcess",true) ;
        map.put("billIds",ids) ;
        map.put("backAddress",initService.querySysParamsByCode(Constants.BACK_SERVER_ADDRESS).getParamValue()) ;
        return new ModelAndView("printPurchaseBill","params",map);
    }

    @PostMapping("/queryPrintPurchaseBill")
    @ChoiceDataSource
    public JsonResult<List<PurchaseBill>> queryPrintPurchaseBill(@RequestParam("billIds") List<Long> billIds) {
        List<PurchaseBill> result = service.queryPrintPurchaseBill(billIds) ;
        return new JsonResult(true, ResultCode.SUCCESS,result);
    }

    @PostMapping("/queryPlan")
    @ChoiceDataSource
    public JsonResult<List<PurchaseBillDetails>> queryPlan(@RequestBody PurchasePlanDto dto) {
        List<PurchaseBillDetails> result = service.queryPlan(dto) ;
        return new JsonResult(true, ResultCode.SUCCESS,result);
    }

    @PostMapping("/queryPurchaseSummary")
    @ChoiceDataSource
    public JsonResult<PurchaseSummaryResult> queryPurchaseSummary(@RequestBody PurchaseSummaryDto dto) {
        List<PurchaseBillDetails> result = service.queryPurchaseSummary(dto) ;
        PurchaseSummaryResult psr = new PurchaseSummaryResult() ;
        psr.setDetails(result);
        psr.setTotalMoney(service.queryPurchaseSummaryTotalMoney(dto));
        return new JsonResult(true, ResultCode.SUCCESS,psr);
    }

    @GetMapping("/downloadPlan")
    @ChoiceDataSource
    public void downloadPlan(PurchasePlanDto dto,
            HttpServletResponse response, HttpServletRequest request) throws IOException {
        setDownload(response,excel);
        String val = request.getParameter("originalProcess") ;
        if (StringUtils.isEmpty(val) == false) {
            dto.setOriginalProcess(Boolean.valueOf(val));
        }
        dto.setKitchen(Constants.KITCHEN_FOOD.equals(this.getSysUser().getFoodSupplyType()));
        excel.downloadPurchasePlanExcel(dto,
                Constants.EXCEL_PURCHASE_TEMPLATE,response.getOutputStream());
    }

    @GetMapping("/printPurchasePlan")
    public ModelAndView printPurchasePlan(PurchasePlanDto dto,HttpServletRequest request) {
        dto.setBackAddress(initService.querySysParamsByCode(Constants.BACK_SERVER_ADDRESS).getParamValue());
        String val = request.getParameter("originalProcess") ;
        if (StringUtils.isEmpty(val) == false) {
            dto.setOriginalProcess(Boolean.valueOf(val));
        }
        dto.setKitchen(Constants.KITCHEN_FOOD.equals(this.getSysUser().getFoodSupplyType()));
        return new ModelAndView("printPurchasePlan","params",dto);
    }

    @GetMapping("/printPurchaseSummary")
    public ModelAndView printPurchaseSummary(
            PurchaseSummaryDto dto,HttpServletRequest request) {
        dto.setBackAddress(initService.querySysParamsByCode(Constants.BACK_SERVER_ADDRESS).getParamValue());
        String val = request.getParameter("originalProcess") ;
        if (StringUtils.isEmpty(val) == false) {
            dto.setOriginalProcess(Boolean.valueOf(val));
        }
        return new ModelAndView("printPurchaseSummary","params",dto);
    }

    @GetMapping("/downloadPurchaseSummary")
    @ChoiceDataSource
    public void downloadPurchaseSummary(PurchaseSummaryDto dto,
        HttpServletResponse response, HttpServletRequest request) throws IOException {
        setDownload(response,excel);
        String val = request.getParameter("originalProcess") ;
        if (StringUtils.isEmpty(val) == false) {
            dto.setOriginalProcess(Boolean.valueOf(val));
        }
        excel.downloadPurchaseSummaryExcel(dto,
                Constants.EXCEL_PURCHASE_SUMMARY_TEMPLATE,response.getOutputStream());
    }

    @GetMapping("/downloadCredentials")
    @ChoiceDataSource
    public void downloadCredentials(
            @RequestParam("fileName") String fileName,
            HttpServletResponse response) throws IOException {
        setDownload(response,fileName);
        StringBuilder imageSavePath = new StringBuilder();
        imageSavePath.append(initService.querySysParamsByCode(Constants.CREDENTIALS_PATH).getParamValue()) ;
        imageSavePath.append(this.getSysUser().getDb()).append('/').append(fileName) ;
        ReadImage.readImage(imageSavePath.toString(),response);
    }

    @GetMapping("/downloadSupplierTemplate")
    @ChoiceDataSource
    public void downloadSupplierTemplate(
            HttpServletResponse response) throws IOException {
        setDownload(response,"supplierTemplate.xlsx");
        StringBuilder imageSavePath = new StringBuilder();
        imageSavePath.append(initService.querySysParamsByCode(Constants.EXCEL_TEMPLATE_PATH).getParamValue()) ;
        imageSavePath.append("supplierTemplate.xlsx") ;
        ReadImage.readImage(imageSavePath.toString(),response);
    }

    @PostMapping("/uploadSupplier")
    @ChoiceDataSource
    public JsonResult<String> uploadSupplier(MultipartFile file) throws IOException {
        int pos = file.getOriginalFilename().lastIndexOf('.') ;
        String suffix =file.getOriginalFilename().substring(pos + 1);
        Workbook workbook = null ;
        try {
            workbook = Excel.getWorkbook(file.getInputStream(),suffix) ;
            String result = excel.uploadSupplierExcel(workbook);
            return result == null ? new JsonResult(true, "上传成功") :
                    new JsonResult(false,result) ;
        } finally {
            FileTools.close(workbook);
        }
    }

    @GetMapping("/clearSupplier")
    @ChoiceDataSource
    public JsonResult<String> clearSupplier() {
        String result = service.truncateSupplier();
        return result == null ? new JsonResult(true,"清理成功"):
                new JsonResult(false,result);
    }

}
